package com.aduerr.v1shouyin.mvp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.CardType;
import com.aduerr.v1shouyin.entity.KouBeiHeXiaoListEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.aduerr.v1shouyin.App.getApp;


/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2018/10/23 19:19
 * @change
 * @chang time
 * @class describe
 */

public class KouBeiHeXiaoRecordActivity extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.stickylist_1)
    StickyListHeadersListView stickylist;
    @BindView(R.id.srfv)
    SmartRefreshLayout srl;
    @BindView(R.id.empty_view)
    View empty_view;
    ArrayList<KouBeiHeXiaoListEntity.DataBean.ListBean> bodylist = new ArrayList<>();
    //请求,码 页数
    private int pager = 1;
    //根据页码判断是否还有更多的数据
    private boolean hasMore = false;
    private stickListAdpterKouBei stickListAdpter;
    private int headsize;
    private TextView tvEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_koubei_hexiao_record);
        ButterKnife.bind(this);
        tvTitle.setText("口碑核销记录");
        initView();
        initData();
    }

    void initView() {


        stickListAdpter = new stickListAdpterKouBei(this);
        stickylist.setAdapter(stickListAdpter);
        stickylist.setVerticalScrollBarEnabled(false);
        stickylist.setFastScrollEnabled(false);
        tvEmpty = (TextView) empty_view.findViewById(R.id.tv_empty);

        srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                hasMore = true;
//                pager = pager + 1;
//                loadMoreData(pager);
//                srl.setLoading(false);
                if(!srl.isRefreshing()) {
                    new Handler().postDelayed(() -> {
                        pager = pager + 1;

                        loadMoreData(pager);
                        // 加载完数据设置为不加载状态，将加载进度收起来
                        if(srl != null) {
                            srl.finishLoadmore();
                        }
                    }, 2000);

                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initData();
                refreshlayout.finishRefresh();
//                srl.setRefreshing(false);
//                srl.setLoading(false);
            }
        });
    }

    @OnClick({R.id.img_back})
    public void OnViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
        }
    }


    //上拉加载数据
    private void loadMoreData(int pager) {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", pager + "");
        addParams.put("type", "1");
//        heXiaoAllFregmenet.showProgress();
        APIRetrofit.getAPIService().useKoubeiQuanList(RXRequest.getXingPosParams(addParams, this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KouBeiHeXiaoListEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull KouBeiHeXiaoListEntity kouBeiHeXiaoListEntity) {
//                        if (isViewAttached())
                        int success = kouBeiHeXiaoListEntity.getSuccess();
                        if(success == 1) {
                            //请求成功后整合数据
                            onHexiaoAllFragView(kouBeiHeXiaoListEntity);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(getApp().getApplicationContext(), "网络异常",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(getApp().getApplicationContext(), "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(getApp().getApplicationContext(), "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    //下啦刷新
    public void initData() {
//        getPresenter().getHexiaoAllfragPresenter();
        pager = 1;
        getDataRefres(KouBeiHeXiaoRecordActivity.this, pager + "");
    }

    private void getDataRefres(Context mContext, String page) {

        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", "1");
//        heXiaoAllFregmenet.showProgress();
        APIRetrofit.getAPIService().useKoubeiQuanList(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KouBeiHeXiaoListEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull KouBeiHeXiaoListEntity kouBeiHeXiaoListEntity) {
                        int success = kouBeiHeXiaoListEntity.getSuccess();
                        if(success == 1) {//请求成功后整合数据
//                            if (kaQuanXiangQingEntity.getData().size() < 0) {
//                                empty_view.setVisibility(View.VISIBLE);
//                                tvEmpty.setText("暂没有该类型的卡券核销记录");
//                            }else {
                            onHexiaoAllFragView(kouBeiHeXiaoListEntity);
//                            }
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(getApp().getApplicationContext(), "网络异常",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(getApp().getApplicationContext(), "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
//                            Log.e("onError:", "error:" + e.getMessage());//R.string
//                            .checknet +
                            Toast.makeText(getApp().getApplicationContext(),
                                    e.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    //从网络上请求下来的数据在
    public void onHexiaoAllFragView(KouBeiHeXiaoListEntity kouBeiHeXiaoListEntity) {
//        srl.setRefreshing(false);
//        Log.e(TAG, "onHexiaoAllFragView: " + hasMore);
//        if (kaQuanXiangQingEntity.getPageCount() > pager) {
//            //有更多的数据
//            hasMore = true;
//        } else {
//            hasMore = false;
//        }
        //// TODO: 2017/10/24 0024    整合数据,展示列表//上拉加载
        if(hasMore) {
            if(kouBeiHeXiaoListEntity.getSuccess() == 1) {
                List<KouBeiHeXiaoListEntity.DataBean> data =
                        kouBeiHeXiaoListEntity.getData();
                int size = data.size();
                //判断数据时候为空
                if(size == 0) {
                    ToastUtils.showToast(KouBeiHeXiaoRecordActivity.this, "没有更多的数据了");
                    return;
                }
                if(size > 0) {
                    for(int i = 0; i < size; i++) {
                        KouBeiHeXiaoListEntity.DataBean dataBean = data.get(i);
                        List<KouBeiHeXiaoListEntity.DataBean.ListBean> list =
                                dataBean.getList();
                        for(KouBeiHeXiaoListEntity.DataBean.ListBean listBean : list) {
                            listBean.setHeadId(i + headsize - 1);
                            bodylist.add(listBean);
                        }
                        //头部id需要整合
                        headsize++;
                    }
                    if(stickListAdpter != null) {
                        stickListAdpter.setBodyList(bodylist);
                    }

                }

            }

        } else {//下啦刷新
            if(kouBeiHeXiaoListEntity.getSuccess() == 1) {
                List<KouBeiHeXiaoListEntity.DataBean> data =
                        kouBeiHeXiaoListEntity.getData();
                int size = data.size();
                headsize = size;
                //判断数据时候为空
                if(size > 0) {
                    //下啦刷新前把数据清空
                    empty_view.setVisibility(View.GONE);
                    stickylist.setVisibility(View.VISIBLE);
                    bodylist.clear();
                    for(int i = 0; i < size; i++) {
                        KouBeiHeXiaoListEntity.DataBean dataBean = data.get(i);
                        List<KouBeiHeXiaoListEntity.DataBean.ListBean> list =
                                dataBean.getList();
                        for(KouBeiHeXiaoListEntity.DataBean.ListBean listBean : list) {
                            listBean.setHeadId(i);
                            bodylist.add(listBean);
                        }
                    }

                    if(stickListAdpter != null) {
                        stickListAdpter.setBodyList(bodylist);
                    }

                } else {
//                    Log.e(TAG, "onHexiaoAllFragView: " + hasMore);
                    stickylist.setVisibility(View.GONE);
                    empty_view.setVisibility(View.VISIBLE);
                    tvEmpty.setText("暂没有该类型的卡券核销记录");
                }
            }
        }

    }

    class stickListAdpterKouBei extends BaseAdapter implements StickyListHeadersAdapter {
        private Context context;
        private List<KouBeiHeXiaoListEntity.DataBean.ListBean> bodyList =
                new ArrayList<>();

        public stickListAdpterKouBei(FragmentActivity activity) {
            this.context = activity;
        }

        //整合好的数据
        public void setBodyList(List<KouBeiHeXiaoListEntity.DataBean.ListBean> bodylist) {
            this.bodyList = bodylist;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return bodyList.size() != 0 ? bodyList.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return bodyList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            stickListAdpterKouBei.BodyHolder bodyHolder;
            if(convertView == null) {
                convertView =
                        LayoutInflater.from(context).inflate(R.layout.item_fragment_hexiaokoubei, parent, false);
                bodyHolder = new BodyHolder(convertView);
                convertView.setTag(bodyHolder);
            } else {
                bodyHolder = (stickListAdpterKouBei.BodyHolder) convertView.getTag();
            }
            //条目的设置数据
            bodyHolder.tv_hx_title.setText(bodyList.get(position).getName());
            bodyHolder.tv_hx_zhekou.setText(bodyList.get(position).getDescription());
            String usetime = bodyList.get(position).getUsetime();
            String[] split = usetime.split(" ");
            if(split.length >= 2) {
                bodyHolder.tv_hx_time.setText(split[1]);
            } else {
                bodyHolder.tv_hx_time.setText("");
            }

            bodyHolder.tv_hx_seller.setText(bodyList.get(position).getSiteusername());
//            //设置数据
//            String paytype = bodyList.get(position).getPaytype();

            convertView.setOnClickListener(v -> {
                KouBeiHeXiaoListEntity.DataBean.ListBean listBean =
                        bodyList.get(position);
                Intent intent = new Intent(KouBeiHeXiaoRecordActivity.this,
                        CardDetailNewActivity.class);
                intent.putExtra("type", CardType.KOUBEI.name());
                intent.putExtra("Data", listBean);
                intent.putExtra("tag", "koubei");
//                    intent.putExtra("erWeiMaResult", erWeiMaResult);
                startActivity(intent);
            });
            return convertView;
        }

        @Override
        public View getHeaderView(int position, View convertView, ViewGroup parent) {
            stickListAdpterKouBei.HeadHolder headHolder;
            if(convertView == null) {
                convertView =
                        LayoutInflater.from(context).inflate(R.layout.item_pmr_header_hexiao, parent, false);
                headHolder = new stickListAdpterKouBei.HeadHolder(convertView);
                convertView.setTag(headHolder);
            } else {
                headHolder = (stickListAdpterKouBei.HeadHolder) convertView.getTag();
            }
            //设置数据
            headHolder.tvTime.setText(bodyList.get(position).getDate());
            return convertView;
        }

        @Override
        public long getHeaderId(int position) {
            return bodyList.get(position).getHeadId();
        }

        //头部的内部类
        class HeadHolder {
            private TextView tvTime;

            public HeadHolder(View itemHeadView) {
                tvTime = (TextView) itemHeadView.findViewById(R.id.tv_time);
            }
        }

        //内容的内部类
        class BodyHolder {
            private final TextView tv_hx_title;
            private final TextView tv_hx_zhekou;
            private final TextView tv_hx_time;
            private final TextView tv_hx_seller;

            public BodyHolder(View itemBodyView) {
                tv_hx_title = (TextView) itemBodyView.findViewById(R.id.tv_hx_title);
                tv_hx_zhekou = (TextView) itemBodyView.findViewById(R.id.tv_hx_zhekou);
                tv_hx_time = (TextView) itemBodyView.findViewById(R.id.tv_hx_time);
                tv_hx_seller = (TextView) itemBodyView.findViewById(R.id.tv_hx_seller);
            }
        }

    }
}
